<template>
  <div class="protocol-config">
    <!-- 协议文件管理 -->
    <el-card class="config-card">
      <template #header>
        <div class="card-header">
          <el-icon><Document /></el-icon>
          <span>协议配置管理</span>
          <div class="header-actions">
            <el-button type="primary" @click="openProtocolDialog()">
              <el-icon><Plus /></el-icon>
              新建协议
            </el-button>
            <el-button @click="loadProtocols" :loading="loading">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索过滤 -->
      <div class="filter-section">
        <el-row :gutter="20" class="mb-3">
          <el-col :xs="24" :sm="8">
            <el-input 
              v-model="searchKeyword" 
              placeholder="搜索协议名称"
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :xs="24" :sm="8">
            <el-select 
              v-model="filterCategory" 
              placeholder="协议分类"
              clearable
              @change="handleFilter"
              style="width: 100%"
            >
              <el-option label="全部分类" value="" />
              <el-option label="Modbus" value="modbus" />
              <el-option label="能源设备" value="energy" />
              <el-option label="工控设备" value="industrial" />
              <el-option label="自定义" value="custom" />
            </el-select>
          </el-col>
          <el-col :xs="24" :sm="8">
            <el-select 
              v-model="sortBy" 
              placeholder="排序方式"
              @change="handleSort"
              style="width: 100%"
            >
              <el-option label="按名称" value="name" />
              <el-option label="按修改时间" value="modified" />
              <el-option label="按创建时间" value="created" />
            </el-select>
          </el-col>
        </el-row>
      </div>

      <!-- 协议文件列表 -->
      <div class="protocol-grid">
        <div 
          v-for="protocol in filteredProtocols" 
          :key="protocol.name"
          class="protocol-card"
          @click="editProtocol(protocol)"
        >
          <div class="protocol-header">
            <div class="protocol-icon">
              <el-icon size="20" :color="getCategoryColor(protocol.category)">
                <Document />
              </el-icon>
            </div>
            <div class="protocol-actions">
              <el-dropdown @command="handleProtocolAction" trigger="click">
                <el-button type="text" size="small">
                  <el-icon><MoreFilled /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item :command="{action: 'edit', protocol}">编辑</el-dropdown-item>
                    <el-dropdown-item :command="{action: 'duplicate', protocol}">复制</el-dropdown-item>
                    <el-dropdown-item :command="{action: 'export', protocol}">导出</el-dropdown-item>
                    <el-dropdown-item :command="{action: 'delete', protocol}" divided>删除</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
          
          <div class="protocol-content">
            <h4 class="protocol-name">{{ protocol.name }}</h4>
            <p class="protocol-description">{{ protocol.description || '暂无描述' }}</p>
            
            <div class="protocol-meta">
              <el-tag :type="getCategoryTagType(protocol.category)" size="small">
                {{ getCategoryName(protocol.category) }}
              </el-tag>
              <span class="protocol-size">{{ formatFileSize(protocol.size) }}</span>
            </div>
            
            <div class="protocol-footer">
              <span class="protocol-modified">{{ formatTime(protocol.modified) }}</span>
              <div class="protocol-stats">
                <span v-if="protocol.registers">{{ protocol.registers }}寄存器</span>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 空状态 -->
        <div v-if="filteredProtocols.length === 0" class="empty-state">
          <el-empty description="没有找到协议文件">
            <el-button type="primary" @click="openProtocolDialog()">新建协议</el-button>
          </el-empty>
        </div>
      </div>
    </el-card>

    <!-- 协议编辑对话框 -->
    <el-dialog 
      :title="dialogTitle"
      v-model="protocolDialogVisible" 
      width="80%"
      :fullscreen="isFullscreen"
      :before-close="handleDialogClose"
    >
      <template #header>
        <div class="dialog-header">
          <span>{{ dialogTitle }}</span>
          <div class="header-buttons">
            <el-button @click="toggleFullscreen" type="text" size="small">
              <el-icon><FullScreen v-if="!isFullscreen" /><Aim v-else /></el-icon>
            </el-button>
          </div>
        </div>
      </template>

      <el-row :gutter="20">
        <!-- 左侧：协议信息 -->
        <el-col :xs="24" :lg="8">
          <el-card class="protocol-info-card">
            <template #header>
              <span>协议信息</span>
            </template>
            
            <el-form
              ref="protocolFormRef"
              :model="currentProtocol"
              :rules="protocolRules"
              label-width="100px"
              size="default"
            >
              <el-form-item label="协议名称" prop="name" required>
                <el-input 
                  v-model="currentProtocol.name" 
                  placeholder="请输入协议名称"
                  :disabled="isEditing"
                />
              </el-form-item>

              <el-form-item label="厂商" prop="vendor">
                <el-input 
                  v-model="currentProtocol.protocol_info.vendor" 
                  placeholder="设备厂商名称"
                />
              </el-form-item>

              <el-form-item label="设备型号" prop="model">
                <el-input 
                  v-model="currentProtocol.protocol_info.model" 
                  placeholder="设备型号"
                />
              </el-form-item>

              <el-form-item label="协议版本" prop="version">
                <el-input 
                  v-model="currentProtocol.protocol_info.version" 
                  placeholder="如: v1.0.0"
                />
              </el-form-item>

              <el-form-item label="协议分类" prop="category" required>
                <el-select 
                  v-model="currentProtocol.category" 
                  placeholder="选择分类"
                  style="width: 100%"
                >
                  <el-option label="Modbus" value="modbus" />
                  <el-option label="能源设备" value="energy" />
                  <el-option label="工控设备" value="industrial" />
                  <el-option label="自定义" value="custom" />
                </el-select>
              </el-form-item>

              <el-form-item label="协议描述" prop="description">
                <el-input 
                  v-model="currentProtocol.protocol_info.description" 
                  type="textarea"
                  :rows="3"
                  placeholder="协议描述信息"
                  maxlength="255"
                  show-word-limit
                />
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>

        <!-- 右侧：协议内容编辑器 -->
        <el-col :xs="24" :lg="16">
          <el-card class="protocol-editor-card">
            <template #header>
              <div class="editor-header">
                <span>协议内容</span>
                <div class="editor-actions">
                  <el-button-group size="small">
                    <el-button 
                      :type="editorMode === 'visual' ? 'primary' : ''"
                      @click="editorMode = 'visual'"
                    >
                      可视化编辑
                    </el-button>
                    <el-button 
                      :type="editorMode === 'json' ? 'primary' : ''"
                      @click="editorMode = 'json'"
                    >
                      JSON编辑
                    </el-button>
                  </el-button-group>
                  <el-button @click="validateProtocol" size="small">
                    <el-icon><Check /></el-icon>
                    验证
                  </el-button>
                </div>
              </div>
            </template>

            <!-- 可视化编辑模式 -->
            <div v-if="editorMode === 'visual'" class="visual-editor">
              <el-tabs v-model="activeTab" type="card">
                <el-tab-pane label="数据点配置" name="data_points">
                  <div class="data-points-editor">
                    <div class="data-points-toolbar">
                      <el-button type="primary" size="small" @click="addDataPoint">
                        <el-icon><Plus /></el-icon>
                        添加数据点
                      </el-button>
                      <el-dropdown @command="loadSpecificTemplate" size="small">
                        <el-button size="small">
                          <el-icon><Download /></el-icon>
                          加载模板
                          <el-icon class="el-icon--right"><ArrowDown /></el-icon>
                        </el-button>
                        <template #dropdown>
                          <el-dropdown-menu>
                            <el-dropdown-item command="energy_meter">能源设备模板 (10个数据点)</el-dropdown-item>
                            <el-dropdown-item command="modbus_basic">基础Modbus模板 (3个数据点)</el-dropdown-item>
                            <el-dropdown-item command="industrial_plc">工控PLC模板 (3个数据点)</el-dropdown-item>
                            <el-dropdown-item command="auto" divided>智能推荐 (根据分类)</el-dropdown-item>
                          </el-dropdown-menu>
                        </template>
                      </el-dropdown>
                    </div>
                    
                    <el-table :data="currentProtocol.data_points" stripe max-height="400">
                      <el-table-column prop="name" label="标识名称" width="140">
                        <template #default="{ row, $index }">
                          <el-input 
                            v-model="row.name" 
                            size="small"
                            placeholder="如: grid_voltage_A"
                          />
                        </template>
                      </el-table-column>
                      
                      <el-table-column prop="chinese_name" label="中文名称" width="120">
                        <template #default="{ row, $index }">
                          <el-input 
                            v-model="row.chinese_name" 
                            size="small"
                            placeholder="如: 电网电压A相"
                          />
                        </template>
                      </el-table-column>
                      
                      <el-table-column prop="address" label="地址" width="80">
                        <template #default="{ row, $index }">
                          <el-input-number 
                            v-model="row.address" 
                            size="small"
                            :min="0"
                            :max="65535"
                            controls-position="right"
                          />
                        </template>
                      </el-table-column>
                      
                      <el-table-column prop="register_type" label="寄存器类型" width="100">
                        <template #default="{ row, $index }">
                          <el-select v-model="row.register_type" size="small">
                            <el-option label="Holding" value="holding" />
                            <el-option label="Input" value="input" />
                          </el-select>
                        </template>
                      </el-table-column>
                      
                      <el-table-column prop="length" label="长度" width="70">
                        <template #default="{ row, $index }">
                          <el-input-number 
                            v-model="row.length" 
                            size="small"
                            :min="1"
                            :max="4"
                            controls-position="right"
                          />
                        </template>
                      </el-table-column>
                      
                      <el-table-column prop="data_type" label="数据类型" width="100">
                        <template #default="{ row, $index }">
                          <el-select v-model="row.data_type" size="small">
                            <el-option label="UInt16" value="uint16" />
                            <el-option label="Int16" value="int16" />
                            <el-option label="UInt32" value="uint32" />
                            <el-option label="Int32" value="int32" />
                            <el-option label="Float32" value="float32" />
                          </el-select>
                        </template>
                      </el-table-column>
                      
                      <el-table-column prop="byte_order" label="字节序" width="100">
                        <template #default="{ row, $index }">
                          <el-select v-model="row.byte_order" size="small">
                            <el-option label="大端" value="big_endian" />
                            <el-option label="小端" value="little_endian" />
                          </el-select>
                        </template>
                      </el-table-column>
                      
                      <el-table-column prop="coefficient" label="系数" width="90">
                        <template #default="{ row, $index }">
                          <el-input-number 
                            v-model="row.coefficient" 
                            size="small"
                            :precision="6"
                            :step="0.001"
                            controls-position="right"
                          />
                        </template>
                      </el-table-column>
                      
                      <el-table-column prop="offset" label="偏移" width="80">
                        <template #default="{ row, $index }">
                          <el-input-number 
                            v-model="row.offset" 
                            size="small"
                            :precision="2"
                            controls-position="right"
                          />
                        </template>
                      </el-table-column>
                      
                      <el-table-column prop="unit" label="单位" width="70">
                        <template #default="{ row, $index }">
                          <el-input 
                            v-model="row.unit" 
                            size="small"
                            placeholder="V/A/kW"
                          />
                        </template>
                      </el-table-column>
                      
                      <el-table-column prop="range" label="范围" width="120">
                        <template #default="{ row, $index }">
                          <div style="display: flex; gap: 4px; align-items: center;">
                            <el-input-number 
                              v-model="row.range.min" 
                              size="small"
                              style="width: 50px;"
                              controls-position="right"
                            />
                            <span>-</span>
                            <el-input-number 
                              v-model="row.range.max" 
                              size="small"
                              style="width: 50px;"
                              controls-position="right"
                            />
                          </div>
                        </template>
                      </el-table-column>
                      
                      <el-table-column prop="decimal_places" label="小数位" width="80">
                        <template #default="{ row, $index }">
                          <el-input-number 
                            v-model="row.decimal_places" 
                            size="small"
                            :min="0"
                            :max="6"
                            controls-position="right"
                          />
                        </template>
                      </el-table-column>
                      
                      <el-table-column prop="description" label="描述" min-width="120">
                        <template #default="{ row, $index }">
                          <el-input 
                            v-model="row.description" 
                            size="small"
                            placeholder="数据点描述"
                          />
                        </template>
                      </el-table-column>
                      
                      <el-table-column label="操作" width="120" fixed="right">
                        <template #default="{ row, $index }">
                          <el-button 
                            type="primary" 
                            size="small" 
                            @click="editDataPoint(row, $index)"
                          >
                            <el-icon><Edit /></el-icon>
                          </el-button>
                          <el-button 
                            type="danger" 
                            size="small" 
                            @click="removeDataPoint($index)"
                          >
                            <el-icon><Delete /></el-icon>
                          </el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                </el-tab-pane>

                <el-tab-pane label="通信参数" name="communication">
                  <div class="communication-config">
                    <el-form :model="currentProtocol.connection" label-width="120px" size="default">
                      <el-form-item label="默认从站ID">
                        <el-input-number 
                          v-model="currentProtocol.connection.default_slave_id"
                          :min="1"
                          :max="255"
                        />
                      </el-form-item>
                      
                      <el-form-item label="连接超时(ms)">
                        <el-input-number 
                          v-model="currentProtocol.connection.default_timeout"
                          :min="1000"
                          :max="30000"
                          :step="1000"
                        />
                      </el-form-item>
                      
                      <el-form-item label="重试次数">
                        <el-input-number 
                          v-model="currentProtocol.connection.retry_times"
                          :min="1"
                          :max="10"
                        />
                      </el-form-item>
                      
                      <el-form-item label="重试间隔(ms)">
                        <el-input-number 
                          v-model="currentProtocol.connection.retry_interval"
                          :min="100"
                          :max="10000"
                          :step="100"
                        />
                      </el-form-item>
                    </el-form>
                  </div>
                </el-tab-pane>
                
                <el-tab-pane label="功能码" name="function_codes">
                  <div class="function-codes-config">
                    <el-form :model="currentProtocol.function_codes" label-width="200px" size="default">
                      <el-form-item label="读保持寄存器">
                        <el-input 
                          v-model="currentProtocol.function_codes.read_holding_registers"
                          placeholder="0x03"
                        />
                      </el-form-item>
                      
                      <el-form-item label="读输入寄存器">
                        <el-input 
                          v-model="currentProtocol.function_codes.read_input_registers"
                          placeholder="0x04"
                        />
                      </el-form-item>
                      
                      <el-form-item label="写单个寄存器">
                        <el-input 
                          v-model="currentProtocol.function_codes.write_single_register"
                          placeholder="0x06"
                        />
                      </el-form-item>
                      
                      <el-form-item label="写多个寄存器">
                        <el-input 
                          v-model="currentProtocol.function_codes.write_multiple_registers"
                          placeholder="0x10"
                        />
                      </el-form-item>
                    </el-form>
                  </div>
                </el-tab-pane>
                
                <el-tab-pane label="错误码" name="error_codes">
                  <div class="error-codes-config">
                    <div class="error-codes-toolbar">
                      <el-button type="primary" size="small" @click="addErrorCode">
                        <el-icon><Plus /></el-icon>
                        添加错误码
                      </el-button>
                    </div>
                    
                    <el-table :data="errorCodeList" stripe>
                      <el-table-column prop="code" label="错误码" width="120">
                        <template #default="{ row, $index }">
                          <el-input 
                            v-model="row.code" 
                            size="small"
                            placeholder="0x01"
                            @change="updateErrorCode($index, row.code, row.message)"
                          />
                        </template>
                      </el-table-column>
                      
                      <el-table-column prop="message" label="错误描述" min-width="200">
                        <template #default="{ row, $index }">
                          <el-input 
                            v-model="row.message" 
                            size="small"
                            placeholder="错误描述"
                            @change="updateErrorCode($index, row.code, row.message)"
                          />
                        </template>
                      </el-table-column>
                      
                      <el-table-column label="操作" width="80" fixed="right">
                        <template #default="{ row, $index }">
                          <el-button 
                            type="danger" 
                            size="small" 
                            @click="removeErrorCode($index)"
                          >
                            <el-icon><Delete /></el-icon>
                          </el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                </el-tab-pane>
              </el-tabs>
            </div>

            <!-- JSON编辑模式 -->
            <div v-else class="json-editor">
              <el-input
                v-model="protocolJsonContent"
                type="textarea"
                :rows="20"
                placeholder="请输入协议JSON配置..."
                class="json-textarea"
              />
            </div>
          </el-card>
        </el-col>
      </el-row>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="protocolDialogVisible = false">取消</el-button>
          <el-button @click="validateProtocol">验证协议</el-button>
          <el-button type="primary" @click="saveProtocol" :loading="saving">
            {{ isEditing ? '更新' : '创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入协议对话框 -->
    <el-dialog title="导入协议" v-model="importDialogVisible" width="500px">
      <el-upload
        ref="uploadRef"
        :on-change="handleFileUpload"
        :before-upload="() => false"
        :show-file-list="false"
        accept=".json"
        drag
      >
        <div class="upload-content">
          <el-icon size="40" color="#409eff">
            <Upload />
          </el-icon>
          <div class="upload-text">
            <p>将协议文件拖到此处，或<em>点击上传</em></p>
            <p class="upload-tip">只支持 JSON 格式文件</p>
          </div>
        </div>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { 
  Document, Plus, Refresh, Search, MoreFilled, FullScreen, Aim,
  Check, Delete, Upload, Download, Edit, ArrowDown
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { protocolAPI } from '@/utils/api'
import { protocolTemplates, getTemplateByCategory, getTemplateList, getTemplate } from '@/utils/protocolTemplates'

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const protocols = ref([])
const searchKeyword = ref('')
const filterCategory = ref('')
const sortBy = ref('name')

// 对话框相关
const protocolDialogVisible = ref(false)
const importDialogVisible = ref(false)
const isEditing = ref(false)
const isFullscreen = ref(false)
const protocolFormRef = ref()
const uploadRef = ref()

// 编辑器相关
const editorMode = ref('visual')
const activeTab = ref('data_points')
const protocolJsonContent = ref('')

// 当前编辑的协议
const currentProtocol = reactive({
  name: '',
  category: 'custom',
  protocol_info: {
    vendor: '',
    model: '',
    version: '1.0.0',
    description: ''
  },
  connection: {
    default_slave_id: 1,
    default_timeout: 3000,
    retry_times: 3,
    retry_interval: 1000
  },
  data_points: [],
  function_codes: {
    read_holding_registers: '0x03',
    read_input_registers: '0x04',
    write_single_register: '0x06',
    write_multiple_registers: '0x10'
  },
  error_codes: {},
  size: 0,
  modified: null,
  created: null
})

// 错误码列表
const errorCodeList = ref([])

// 表单验证规则
const protocolRules = {
  name: [
    { required: true, message: '请输入协议名称', trigger: 'blur' },
    { min: 2, max: 50, message: '协议名称长度在 2 到 50 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_-]+$/, message: '协议名称只能包含字母、数字、下划线和横线', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择协议分类', trigger: 'change' }
  ]
}

// 计算属性
const filteredProtocols = computed(() => {
  let filtered = protocols.value

  // 关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(protocol => 
      protocol.name.toLowerCase().includes(keyword) ||
      (protocol.description && protocol.description.toLowerCase().includes(keyword))
    )
  }

  // 分类过滤
  if (filterCategory.value) {
    filtered = filtered.filter(protocol => protocol.category === filterCategory.value)
  }

  // 排序
  filtered.sort((a, b) => {
    switch (sortBy.value) {
      case 'name':
        return a.name.localeCompare(b.name)
      case 'modified':
        return new Date(b.modified) - new Date(a.modified)
      case 'created':
        return new Date(b.created) - new Date(a.created)
      default:
        return 0
    }
  })

  return filtered
})

const dialogTitle = computed(() => {
  return isEditing.value ? `编辑协议 - ${currentProtocol.name}` : '新建协议'
})

// 方法
const loadProtocols = async () => {
  try {
    loading.value = true
    const result = await protocolAPI.getProtocolList()
    if (Array.isArray(result)) {
      protocols.value = result
    } else if (Array.isArray(result?.protocols)) {
      protocols.value = result.protocols.map(item => ({
        name: item.name || item.label || '',
        label: item.label || item.name || '',
        value: item.value,
        path: item.value,
        category: item.category || 'custom',
        description: item.description || '',
        modified: item.modified || null,
        created: item.created || null,
        size: item.size || 0,
        categories: item.categories || []
      }))
    } else {
      protocols.value = []
    }
  } catch (error) {
    ElMessage.error('加载协议列表失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

const openProtocolDialog = (protocol = null) => {
  if (protocol) {
    isEditing.value = true
    Object.assign(currentProtocol, protocol)
    
    // 处理错误码列表
    errorCodeList.value = Object.entries(protocol.error_codes || {}).map(([code, message]) => ({
      code,
      message
    }))
    
    protocolJsonContent.value = JSON.stringify(protocol, null, 2)
  } else {
    isEditing.value = false
    resetCurrentProtocol()
    protocolJsonContent.value = JSON.stringify(currentProtocol, null, 2)
  }
  protocolDialogVisible.value = true
}

const resetCurrentProtocol = () => {
  Object.assign(currentProtocol, {
    name: '',
    category: 'custom',
    protocol_info: {
      vendor: '',
      model: '',
      version: '1.0.0',
      description: ''
    },
    connection: {
      default_slave_id: 1,
      default_timeout: 3000,
      retry_times: 3,
      retry_interval: 1000
    },
    data_points: [],
    function_codes: {
      read_holding_registers: '0x03',
      read_input_registers: '0x04',
      write_single_register: '0x06',
      write_multiple_registers: '0x10'
    },
    error_codes: {},
    size: 0,
    modified: null,
    created: null
  })
  errorCodeList.value = []
}

const editProtocol = (protocol) => {
  openProtocolDialog(protocol)
}

const saveProtocol = async () => {
  if (!protocolFormRef.value) return

  try {
    const valid = await protocolFormRef.value.validate()
    if (!valid) return

    saving.value = true

    // 同步JSON编辑器内容
    if (editorMode.value === 'json') {
      try {
        const parsedData = JSON.parse(protocolJsonContent.value)
        Object.assign(currentProtocol, parsedData)
        
        // 处理错误码列表
        if (parsedData.error_codes) {
          errorCodeList.value = Object.entries(parsedData.error_codes).map(([code, message]) => ({
            code,
            message
          }))
        }
      } catch (error) {
        ElMessage.error('JSON格式错误，请检查协议配置')
        return
      }
    } else {
      // 同步错误码到对象
      currentProtocol.error_codes = {}
      errorCodeList.value.forEach(item => {
        if (item.code && item.message) {
          currentProtocol.error_codes[item.code] = item.message
        }
      })
      
      protocolJsonContent.value = JSON.stringify(currentProtocol, null, 2)
    }

    if (isEditing.value) {
      await protocolAPI.updateProtocol(currentProtocol.name, currentProtocol)
      ElMessage.success('协议更新成功')
    } else {
      await protocolAPI.createProtocol(currentProtocol.name, currentProtocol)
      ElMessage.success('协议创建成功')
    }

    protocolDialogVisible.value = false
    loadProtocols()
  } catch (error) {
    ElMessage.error('保存协议失败: ' + error.message)
  } finally {
    saving.value = false
  }
}

const validateProtocol = () => {
  try {
    if (editorMode.value === 'json') {
      JSON.parse(protocolJsonContent.value)
    }
    ElMessage.success('协议配置验证通过')
  } catch (error) {
    ElMessage.error('协议配置验证失败: ' + error.message)
  }
}

const handleProtocolAction = ({ action, protocol }) => {
  switch (action) {
    case 'edit':
      editProtocol(protocol)
      break
    case 'duplicate':
      duplicateProtocol(protocol)
      break
    case 'export':
      exportProtocol(protocol)
      break
    case 'delete':
      deleteProtocol(protocol)
      break
  }
}

const duplicateProtocol = (protocol) => {
  const duplicated = { ...protocol }
  duplicated.name = `${protocol.name}_copy`
  duplicated.created = null
  duplicated.modified = null
  openProtocolDialog(duplicated)
  isEditing.value = false
}

const exportProtocol = (protocol) => {
  const dataStr = JSON.stringify(protocol, null, 2)
  const blob = new Blob([dataStr], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  
  const a = document.createElement('a')
  a.href = url
  a.download = `${protocol.name}.json`
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
  
  ElMessage.success('协议导出成功')
}

const deleteProtocol = async (protocol) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除协议 "${protocol.name}" 吗？此操作不可恢复。`,
      '删除协议',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await protocolAPI.deleteProtocol(protocol.name)
    ElMessage.success('协议删除成功')
    loadProtocols()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除协议失败: ' + error.message)
    }
  }
}

const addDataPoint = () => {
  currentProtocol.data_points.push({
    name: `data_point_${currentProtocol.data_points.length + 1}`,
    chinese_name: '',
    address: 0,
    register_type: 'holding',
    length: 1,
    data_type: 'uint16',
    byte_order: 'big_endian',
    coefficient: 1,
    offset: 0,
    unit: '',
    range: {
      min: 0,
      max: 65535
    },
    decimal_places: 0,
    description: ''
  })
}

const removeDataPoint = (index) => {
  currentProtocol.data_points.splice(index, 1)
}

const editDataPoint = (dataPoint, index) => {
  // 可以添加详细编辑对话框的逻辑
  ElMessage.info('点击数据点可以直接编辑各个字段')
}

const loadTemplateDataPoints = async () => {
  try {
    // 根据当前协议分类获取推荐模板
    const templateData = getTemplateByCategory(currentProtocol.category)
    
    if (templateData.data_points && templateData.data_points.length > 0) {
      // 加载数据点
      currentProtocol.data_points = [...templateData.data_points]
      
      // 同时加载其他配置信息
      if (templateData.connection) {
        Object.assign(currentProtocol.connection, templateData.connection)
      }
      
      if (templateData.function_codes) {
        Object.assign(currentProtocol.function_codes, templateData.function_codes)
      }
      
      if (templateData.error_codes) {
        currentProtocol.error_codes = { ...templateData.error_codes }
        errorCodeList.value = Object.entries(templateData.error_codes).map(([code, message]) => ({
          code,
          message
        }))
      }
      
      // 如果协议信息为空，也可以填入模板建议值
      if (!currentProtocol.protocol_info.vendor && templateData.protocol_info) {
        currentProtocol.protocol_info.vendor = templateData.protocol_info.vendor
        currentProtocol.protocol_info.model = templateData.protocol_info.model
        currentProtocol.protocol_info.description = templateData.protocol_info.description
      }
      
      ElMessage.success(`已加载"${templateData.name}" - ${templateData.data_points.length} 个数据点`)
    } else {
      ElMessage.warning('模板中未找到数据点配置')
    }
  } catch (error) {
    ElMessage.error('加载模板失败: ' + error.message)
  }
}

const loadSpecificTemplate = (templateKey) => {
  try {
    let templateData
    
    if (templateKey === 'auto') {
      // 智能推荐：根据当前协议分类获取模板
      templateData = getTemplateByCategory(currentProtocol.category)
    } else {
      // 加载指定模板
      templateData = getTemplate(templateKey)
    }
    
    if (templateData && templateData.data_points && templateData.data_points.length > 0) {
      // 加载数据点
      currentProtocol.data_points = [...templateData.data_points]
      
      // 同时加载其他配置信息
      if (templateData.connection) {
        Object.assign(currentProtocol.connection, templateData.connection)
      }
      
      if (templateData.function_codes) {
        Object.assign(currentProtocol.function_codes, templateData.function_codes)
      }
      
      if (templateData.error_codes) {
        currentProtocol.error_codes = { ...templateData.error_codes }
        errorCodeList.value = Object.entries(templateData.error_codes).map(([code, message]) => ({
          code,
          message
        }))
      }
      
      // 如果协议信息为空，也可以填入模板建议值（可选）
      if (!currentProtocol.protocol_info.vendor && templateData.protocol_info) {
        currentProtocol.protocol_info.vendor = templateData.protocol_info.vendor
        currentProtocol.protocol_info.model = templateData.protocol_info.model
        currentProtocol.protocol_info.description = templateData.protocol_info.description
      }
      
      const templateDescription = templateKey === 'auto' ? 
        `"${templateData.name}"（智能推荐）` : 
        `"${templateData.name}"`
      
      ElMessage.success(`已加载${templateDescription} - ${templateData.data_points.length} 个数据点`)
    } else {
      ElMessage.warning('所选模板中未找到数据点配置')
    }
  } catch (error) {
    ElMessage.error('加载模板失败: ' + error.message)
  }
}

const addErrorCode = () => {
  const errorCode = {
    code: '0x' + (errorCodeList.value.length + 1).toString(16).padStart(2, '0').toUpperCase(),
    message: ''
  }
  errorCodeList.value.push(errorCode)
  currentProtocol.error_codes[errorCode.code] = errorCode.message
}

const removeErrorCode = (index) => {
  const errorCode = errorCodeList.value[index]
  delete currentProtocol.error_codes[errorCode.code]
  errorCodeList.value.splice(index, 1)
}

const updateErrorCode = (index, code, message) => {
  const oldCode = errorCodeList.value[index].code
  if (oldCode !== code) {
    delete currentProtocol.error_codes[oldCode]
  }
  currentProtocol.error_codes[code] = message
}

const toggleFullscreen = () => {
  isFullscreen.value = !isFullscreen.value
}

const handleDialogClose = () => {
  protocolFormRef.value?.resetFields()
  protocolDialogVisible.value = false
  isFullscreen.value = false
}

const handleFileUpload = (file) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    try {
      const protocolData = JSON.parse(e.target.result)
      const protocol = {
        name: file.name.replace('.json', ''),
        category: 'custom',
        version: '1.0.0',
        ...protocolData
      }
      openProtocolDialog(protocol)
      isEditing.value = false
      importDialogVisible.value = false
    } catch (error) {
      ElMessage.error('协议文件格式错误')
    }
  }
  reader.readAsText(file.raw)
}

const handleSearch = () => {
  // 搜索逻辑在计算属性中实现
}

const handleFilter = () => {
  // 过滤逻辑在计算属性中实现
}

const handleSort = () => {
  // 排序逻辑在计算属性中实现
}

// 工具函数
const formatTime = (timestamp) => {
  if (!timestamp) return '--'
  return new Date(timestamp).toLocaleDateString()
}

const formatFileSize = (bytes) => {
  if (!bytes) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]
}

const getCategoryColor = (category) => {
  const colors = {
    modbus: '#1890ff',
    energy: '#52c41a',
    industrial: '#faad14',
    custom: '#722ed1'
  }
  return colors[category] || '#8c8c8c'
}

const getCategoryTagType = (category) => {
  const types = {
    modbus: 'primary',
    energy: 'success',
    industrial: 'warning',
    custom: ''
  }
  return types[category] || 'info'
}

const getCategoryName = (category) => {
  const names = {
    modbus: 'Modbus',
    energy: '能源设备',
    industrial: '工控设备',
    custom: '自定义'
  }
  return names[category] || category
}

// 监听编辑器模式变化
watch(editorMode, (newMode) => {
  if (newMode === 'json') {
    // 同步错误码到对象
    currentProtocol.error_codes = {}
    errorCodeList.value.forEach(item => {
      if (item.code && item.message) {
        currentProtocol.error_codes[item.code] = item.message
      }
    })
    protocolJsonContent.value = JSON.stringify(currentProtocol, null, 2)
  }
})

// 生命周期
onMounted(() => {
  loadProtocols()
})
</script>

<style scoped>
.protocol-config {
  max-width: 1200px;
  margin: 0 auto;
}

.config-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
}

.header-actions {
  margin-left: auto;
  display: flex;
  gap: 12px;
}

.filter-section {
  margin-bottom: 20px;
  padding: 16px;
  background: #fafafa;
  border-radius: 6px;
}

.protocol-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  min-height: 200px;
}

.protocol-card {
  background: white;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.protocol-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
  border-color: #1890ff;
}

.protocol-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.protocol-icon {
  flex-shrink: 0;
}

.protocol-actions {
  opacity: 0;
  transition: opacity 0.2s ease;
}

.protocol-card:hover .protocol-actions {
  opacity: 1;
}

.protocol-name {
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 8px 0;
  color: #262626;
}

.protocol-description {
  font-size: 14px;
  color: #8c8c8c;
  margin: 0 0 12px 0;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.protocol-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.protocol-size {
  font-size: 12px;
  color: #8c8c8c;
}

.protocol-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #8c8c8c;
}

.protocol-stats {
  text-align: right;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.header-buttons {
  display: flex;
  gap: 8px;
}

.protocol-info-card,
.protocol-editor-card {
  height: 500px;
  margin-bottom: 0;
}

.protocol-editor-card :deep(.el-card__body) {
  height: calc(100% - 55px);
  padding: 0;
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #e8e8e8;
}

.editor-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.visual-editor,
.json-editor {
  height: calc(100% - 60px);
  overflow: auto;
}

.visual-editor :deep(.el-tabs) {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.visual-editor :deep(.el-tabs__content) {
  flex: 1;
  overflow: auto;
  padding: 16px;
}

.data-points-toolbar,
.error-codes-toolbar {
  margin-bottom: 16px;
  text-align: right;
}

.data-points-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.data-points-toolbar .el-button-group {
  margin-left: auto;
}

.communication-config,
.function-codes-config,
.error-codes-config {
  padding: 16px;
}

.json-editor {
  padding: 16px;
}

.json-textarea {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
}

.json-textarea :deep(.el-textarea__inner) {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  line-height: 1.6;
}

.upload-content {
  text-align: center;
  padding: 40px 20px;
}

.upload-text p {
  margin: 8px 0;
}

.upload-text em {
  color: #409eff;
  font-style: normal;
}

.upload-tip {
  font-size: 12px;
  color: #8c8c8c;
}

.empty-state {
  grid-column: 1 / -1;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .protocol-grid {
    grid-template-columns: 1fr;
  }
  
  .header-actions {
    flex-direction: column;
    gap: 8px;
  }
  
  .header-actions .el-button {
    width: 100%;
  }
  
  .protocol-card {
    padding: 12px;
  }
  
  .protocol-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}

@media (max-width: 992px) {
  :deep(.el-dialog) {
    margin: 0 !important;
    width: 100% !important;
    height: 100% !important;
    border-radius: 0;
  }
}
</style>
